import fs from 'fs-extra'
import path from 'path'

export async function listDir (dir: string, fileExts: string[]): Promise<string[]> {
    const out: string[] = []
    await listDirInternal(dir, fileExts, out)
    return out
}

async function listDirInternal (dir: string, fileExts: string[], out: string[]): Promise<void> {
    const files = await fs.readdir(dir)
    for (const f of files) {
        const file = path.join(dir, f)
        const fstat = await fs.stat(file)
        if (fstat.isDirectory()) {
            await listDirInternal(file, fileExts, out)
        } else {
            if (fileExts.includes(path.extname(f))) {
                out.push(file)
            }
        }
    }
}

export async function removeEmptyDirs (dir: string): Promise<void> {
    let files = await fs.readdir(dir)
    if (files.length > 0) {
        for (const f of files) {
            const file = path.join(dir, f)
            const fstat = await fs.stat(file)
            if (fstat.isDirectory()) {
                await removeEmptyDirs(file)
            }
        }
        files = await fs.readdir(dir)
    }
    if (files.length === 0) {
        await fs.remove(dir)
    }
}
